import socket
import threading
import json
from python_redis import PythonRedis

class RedisServer:
    def __init__(self, redis_instance):
        self.redis = redis_instance
        self.config = redis_instance.config
        self.server_socket = None

    def start(self):
        """启动服务器"""
        host = self.config['server']['host']
        port = self.config['server']['port']
        
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((host, port))
        self.server_socket.listen(self.config['performance']['max_connections'])
        
        print(f"服务器启动在 {host}:{port}")
        
        while True:
            client_socket, address = self.server_socket.accept()
            client_thread = threading.Thread(
                target=self.handle_client,
                args=(client_socket, address)
            )
            client_thread.start()

    def handle_client(self, client_socket, address):
        """处理客户端连接"""
        try:
            while True:
                data = client_socket.recv(1024).decode('utf-8')
                if not data:
                    break
                
                try:
                    command = json.loads(data)
                    response = self.process_command(command)
                    client_socket.send(json.dumps(response).encode('utf-8'))
                except json.JSONDecodeError:
                    error_response = {"error": "Invalid JSON format"}
                    client_socket.send(json.dumps(error_response).encode('utf-8'))
                    
        except Exception as e:
            print(f"处理客户端 {address} 时出错: {str(e)}")
        finally:
            client_socket.close()

    def process_command(self, command):
        """处理命令"""
        cmd_type = command.get('type')
        key = command.get('key')
        value = command.get('value')
        
        if cmd_type == 'set':
            expiry = command.get('expiry')
            success = self.redis.set(key, value, ex=expiry)
            return {'success': success}
            
        elif cmd_type == 'get':
            value = self.redis.get(key)
            return {'value': value}
            
        elif cmd_type == 'delete':
            success = self.redis.delete(key)
            return {'success': success}
            
        # Hash 操作
        elif cmd_type == 'hset':
            hash_key = command.get('hash_key')
            success = self.redis.hset(key, hash_key, value)
            return {'success': success}
            
        elif cmd_type == 'hget':
            hash_key = command.get('hash_key')
            value = self.redis.hget(key, hash_key)
            return {'value': value}
            
        # List 操作
        elif cmd_type == 'lpush':
            values = command.get('values', [])
            length = self.redis.lpush(key, *values)
            return {'length': length}
            
        elif cmd_type == 'rpop':
            value = self.redis.rpop(key)
            return {'value': value}
            
        # Set 操作
        elif cmd_type == 'sadd':
            values = command.get('values', [])
            count = self.redis.sadd(key, *values)
            return {'count': count}
            
        elif cmd_type == 'smembers':
            members = self.redis.smembers(key)
            return {'members': members}
            
        return {'error': '未知命令'}
